package dfw

import (
	"dfws/shell"
	"io/ioutil"
	"log"
	"net"
	"os"
	"runtime"
	"strings"
)

func SetDnsDfw(workDir string, domain string) {
	txtRecords, _ := net.LookupTXT(domain)
	isFind := false
	println("TXT:", domain, len(txtRecords))
	if len(txtRecords) > 0 {
		isFind = true
		info, err := SetFwConfig(workDir, domain, txtRecords)
		if err != nil {
			println(info, err)
		} else {
			println(info)
		}
	}
	if !isFind {
		ipRecords, _ := net.LookupIP(domain)
		println("A:", domain, len(ipRecords))
		var ips []string
		for _, ip := range ipRecords {
			ips = append(ips, ip.To4().String())
		}
		if len(ips) > 0 {
			isFind = true
			info, err := SetFwConfig(workDir, domain, ips)
			if err != nil {
				println(info, err)
			} else {
				println(info)
			}
		}
	}
}

/**
 * 判断文件是否存在  存在返回 true 不存在返回false
 */
func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}
func loadIp(workDir string, id string) string {
	var file = workDir + "/" + id + "/" + id + ".ip"
	if !checkFileIsExist(file) {
		return ""
	}
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return ""
	}
	return string(data)
}

func saveIp(workDir string, id string, ips []string) {
	var dir = workDir + "/" + id
	err := os.MkdirAll(dir, 0755)
	if err != nil {
		log.Println("创建目录错误：", dir)
	}
	var file = dir + "/" + id + ".ip"
	data := ""
	for _, ip := range ips {
		data += ip + "\n"
	}
	if err := ioutil.WriteFile(file, []byte(data), 0666); err != nil {
		log.Println(`写入IP数据 error :`, err)
	}
}

func SetFwConfig(workDir string, id string, ips []string) (string, error) {
	if len(ips) < 1 {
		return "无IP数据", nil
	}
	oldIp := loadIp(workDir, id)
	var info string = ""
	if oldIp != "" {
		oldIps := strings.Split(oldIp, "\n")
		if runtime.GOOS == "windows" {
			info = "暂不支持windows操作系统"
			return info, nil
		} else if checkFileIsExist("/etc/debian_version") {
			for _, ip := range oldIps {
				if ip == "" {
					continue
				}
				cmd := "ufw delete allow from " + ip
				stdout, err := shell.Shell(cmd)
				info += stdout
				if err != nil {
					log.Println("删除历史防火墙规则 error :", err, cmd)
				}
			}
		} else if checkFileIsExist("/etc/redhat_release") {
			for _, ip := range oldIps {
				cmd := "firewall-cmd --permanent --zone=trusted --remove-source=" + ip + " && firewall-cmd --reload"
				stdout, err := shell.Shell(cmd)
				info += stdout
				if err != nil {
					log.Println("删除历史防火墙规则 error :", err, cmd)
				}
			}
		}
	}
	if runtime.GOOS == "windows" {
		info = "暂不支持windows操作系统"
		return info, nil
	} else if checkFileIsExist("/etc/debian_version") {
		for _, ip := range ips {
			cmd := "ufw allow from " + ip
			stdout, err := shell.Shell(cmd)
			info += stdout
			if err != nil {
				log.Println("添加防火墙规则 error :", err, cmd)
				return info, err
			}
		}
		saveIp(workDir, id, ips)
		return info + " 成功", nil
	} else if checkFileIsExist("/etc/redhat-release") {
		for _, ip := range ips {
			cmd := "firewall-cmd --permanent --zone=trusted --add-source=" + ip + " && firewall-cmd --reload"
			stdout, err := shell.Shell(cmd)
			info += stdout
			if err != nil {
				log.Println("添加防火墙规则 error :", err, cmd)
				return info, err
			}
		}
		saveIp(workDir, id, ips)
		return info + " 成功", nil
	} else {
		info = "未知的操作系统"
		return info, nil
	}
}
